﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Globalization;

namespace Kalficom.Forms
{
    public partial class frmTaken : Form
    {
        public frmTaken()
        {
            InitializeComponent();
            conf.Icon(this);
        }

        Libraies.db db = new Libraies.db();
        Query.qry_contract query = new Query.qry_contract();
        Libraies.msg msg = new Libraies.msg();
        internal int client_taken_id = 0;
        internal int taken_copy_id = 0;
        internal int cont_id = 0;
        CheckBox[] taken_day, taken_month, taken_week;
        bool ananlyse_refresh = true;
        bool week_refesh = false;
        bool week_load = false;

        private void frmTaken_Load(object sender, EventArgs e)
        {
            // Assign variable checkbox.
            taken_day = new CheckBox[] { chk_d_1, chk_d_2, chk_d_3, chk_d_4, chk_d_5, chk_d_6, chk_d_7 };
            taken_month = new CheckBox[] { chk_m_1, chk_m_2, chk_m_3, chk_m_4, chk_m_5, chk_m_6, chk_m_7, chk_m_8, chk_m_9, chk_m_10, chk_m_11, chk_m_12 };
            taken_week = new CheckBox[] { chk_w_1, chk_w_2, chk_w_3, chk_w_4, chk_w_5, chk_w_6, chk_w_7, chk_w_8, chk_w_9, chk_w_10, chk_w_11, chk_w_12,
                                            chk_w_13, chk_w_14, chk_w_15, chk_w_16, chk_w_17, chk_w_18, chk_w_19, chk_w_20, chk_w_21, chk_w_22, chk_w_23, chk_w_24,
                                            chk_w_25, chk_w_26, chk_w_27, chk_w_28, chk_w_29, chk_w_30, chk_w_31, chk_w_32, chk_w_33, chk_w_34, chk_w_35, chk_w_36,
                                            chk_w_37, chk_w_38, chk_w_39, chk_w_40, chk_w_41, chk_w_42, chk_w_43, chk_w_44, chk_w_45, chk_w_46, chk_w_47, chk_w_48,
                                            chk_w_49, chk_w_50, chk_w_51, chk_w_52};

            // Get product, plan, sector, point, point of surveillance and point of taken information into comboBox
            db.FillDataSet(query.get_product, NPRODUIT);
            db.FillDataSet(query.get_plan, PLANS);
            db.FillDataSet(query.get_sector, SECTEURS);
            db.FillDataSet(query.get_point_surveillance, PTSURV);
            db.FillDataSet(query.get_point_taken, PTPREL);

            // Draw product, plan, sector, point, point of surveillance and point of taken comboBox display two column
            drawComboBox(cboCode, "PRD_CODE", "PRD_LIB");
            drawComboBox(cboType, "PL_CODE", "PL_LIBELLE");
            drawComboBox(cboSector, "SE_CODE", "SE_LIBELLE");
            drawComboBox(cboPointTaken, "PP_CODSURV", "PP_LIBELLE");
            drawComboBox(cboPointSurveillance, "PS_CODE", "PS_LIBELLE");

            cboPointTaken_SelectedIndexChanged(null, null);

            if (this.Tag != null)
            {
                // Unset refresh taken analyze list when combobox value change or radiobutton check change.
                ananlyse_refresh = false;

                // Read taken information 
                db.FillDataSet(string.Format(query.get_taken, this.Tag), k_taken);

                // Set check on rdoCode, rdoPlan or rdoSector
                (new RadioButton[] { rdoCode, rdoPlan, rdoSector })[int.Parse(k_taken.Rows[0]["taken_type"].ToString())].Checked = true;

                // Set value into checkbox of taken days
                set_takenCheckBox(taken_day, k_taken.Rows[0]["days_taken"].ToString());

                // Set value into checkbox of taken months
                set_takenCheckBox(taken_month, k_taken.Rows[0]["months_taken"].ToString());

                // Set value into checkbox of taken years
                set_takenCheckBox(taken_week, k_taken.Rows[0]["years_taken"].ToString());

                // Read analyse taken.
                db.FillDataSet(string.Format(query.get_analy_taken, this.Tag), k_taken_analyze);

                if (taken_copy_id > 0)
                    this.Tag = null;
                else
                {
                    lblTakenStart.Visible = true;
                    txtTakenNext.Visible = true;
                    txtDateTaken.Visible = lblDateTaken.Visible = false;
                    txtTakenLast.Visible = lblTakenLast.Visible = true;
                }

               // Set refresh taken analyze list when combobox value change or radiobutton check change.
                ananlyse_refresh = true;
            }
            else
            {
                if (cboType.Text.Trim() == "") cboType.SelectedIndex = 0;
                if (cboSector.Text.Trim() == "") cboSector.SelectedIndex = 0;
                dtpTakenNext.Value = dtpTaken.Value = DateTime.Parse(db.ExecuteScalar(string.Format(query.get_cont_date, cont_id)));
                analyses_List(0);
            }

            week_refesh = true;
            foreach (CheckBox chk in taken_month) chk_m_1_CheckedChanged(chk, null);
            week_load = true;

            // Set Combobox style
            (new Libraies.ctl()).ComboBox_Style(new ComboBox[] { cboCode, cboPointSurveillance, cboPointTaken, cboSector, cboType });

        }

        private string get_takenString(CheckBox[] chks)
        {
            string result = "";
            int chk_index = 1;
            foreach (CheckBox chk in chks)
            {
                if (chk.Checked) result = (result == "" ? chk_index.ToString() : string.Format("{0}-{1}", result, chk_index)); 
                ++chk_index;
            }
            return result;
        }

        private void set_takenCheckBox(CheckBox[] chks,string value)
        {
            foreach (CheckBox chk in chks) chk.Checked = false;
            foreach (string str in value.Split(char.Parse("-")))
            {
                chks[int.Parse(str)-1].Checked = true;
            }
        }

        private void drawComboBox(ComboBox cbo, string valueField, string displayField)
        {
            // Set DropDownWidth
            cbo.DropDownWidth = 350;
            // Enable the owner draw on the ComboBox.
            cbo.DrawMode = DrawMode.OwnerDrawFixed;
            // Handle the DrawItem event to draw the items.
            cbo.DrawItem += delegate(object cmb, DrawItemEventArgs args)
            {
                // Draw the default background
                args.DrawBackground();

                // The ComboBox is bound to a DataTable,
                // so the items are DataRowView objects.
                DataRowView drv = (DataRowView)cbo.Items[args.Index];

                // Retrieve the value of each column.
                string id = drv[valueField].ToString();
                string name = drv[displayField].ToString();

                // Get the bounds for the first column
                Rectangle r1 = args.Bounds;
                r1.Width /= 3;

                // Draw the text on the first column
                using (SolidBrush sb = new SolidBrush(args.ForeColor))
                {
                    args.Graphics.DrawString(id, args.Font, sb, r1);
                }

                // Draw a line to isolate the columns 
                using (Pen p = new Pen(Color.Black))
                {
                    args.Graphics.DrawLine(p, r1.Right, 0, r1.Right, r1.Bottom);
                }

                // Get the bounds for the second column
                Rectangle r2 = args.Bounds;
                r2.X = (args.Bounds.Width / 3) + 2;
                r2.Width /= 2;

                // Draw the text on the second column
                using (SolidBrush sb = new SolidBrush(args.ForeColor))
                {
                    args.Graphics.DrawString(name, args.Font, sb, r2);
                }
            };
        }

        private void rdoCode_CheckedChanged(object sender, EventArgs e)
        {
            lblPlan.Visible = cboType.Visible = rdoPlan.Checked;
            lblSector.Visible = cboSector.Visible = rdoSector.Checked;
            RadioButton rdo = (RadioButton)sender;
                if (rdo == rdoPlan && cboType.Text.Trim() == "") cboType.SelectedIndex = 0;
                if (rdo == rdoSector && cboSector.Text.Trim() == "") cboSector.SelectedIndex = 0;
            analyses_List(int.Parse(rdo.Tag.ToString()));
        }

        private void analyses_List(int index)
        {
            if (!ananlyse_refresh) return;
            string[] analy = new string[] { query.get_analy_product, query.get_analy_plan, query.get_analy_sector };
            ComboBox[] cbo = new ComboBox[] { cboCode, cboType, cboSector };
            DataTable tbl = new DataTable();
            db.FillDataSet(string.Format(analy[index], db.SqlString(cbo[index].SelectedValue)), k_taken_analyze);
            //if (this.Tag == null) k_taken_analyze.Clear();
            //foreach (DataRow row in tbl.Rows)
            //{
            //    if (k_taken_analyze.Select(string.Format("analyze_code={0} AND analyze_label={1}", db.SqlString(row["analyze_code"]), db.SqlString(row["analyze_label"]))).Length == 0)
            //    {
            //        DataRow r = k_taken_analyze.NewRow();
            //        r["analyze_code"] = row["analyze_code"];
            //        r["analyze_label"] = row["analyze_label"];
            //        r["TO_DO"] = row["TO_DO"];
            //        k_taken_analyze.Rows.Add(r);
            //    }
            //}
            
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!txtTakenNext.Visible) dtpTakenNext.Value = dtpTaken.Value;
            if (!(new Libraies.ctl()).check_ComboValue(new ComboBox[] { cboCode, cboPointSurveillance, cboPointTaken, cboSector, cboType })) return;
            if (DateTime.Parse(db.ExecuteScalar(string.Format(query.get_cont_date, cont_id))) > dtpTaken.Value.Date)
            {
                MessageBox.Show(msg.cont_takenFirstDate, msg.captionMsg, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                txtDateTaken.Focus();
                txtDateTaken.SelectAll();
                return;
            }

            if (Tag != null && taken_copy_id == 0)
            {
                if (txtTakenNext.Text.Trim() == "")
                {
                    MessageBox.Show(msg.cont_takenNextDateBlank, msg.captionMsg, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    txtTakenNext.Focus();
                    txtTakenNext.SelectAll();
                    return;
                }
            }

            if (dtpTakenNext.Value.Date < dtpTaken.Value.Date)
            {
                MessageBox.Show(msg.cont_takenNextDate, msg.captionMsg, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                txtTakenNext.Focus();
                txtTakenNext.SelectAll();
                return;
            }

            string sday = get_takenString(taken_day);
            string smonth = get_takenString(taken_month);
            string sweek = get_takenString(taken_week);

            if (sday == "")
            {
                MessageBox.Show(msg.cont_takenDay, msg.captionMsg, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                chk_d_1.Focus();
                return;
            }

            if (smonth == "")
            {
                MessageBox.Show(msg.cont_takenMonth, msg.captionMsg, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                chk_m_1.Focus();
                return;
            }

            if (sweek == "")
            {
                MessageBox.Show(msg.cont_takenYear, msg.captionMsg, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                chk_w_1.Focus();
                return;
            }

            DataRow row = k_taken.NewRow();
            row["prod_code"] = cboCode.SelectedValue;
            row["taken_type"] = rdoCode.Checked ? 0 : rdoPlan.Checked ? 1 : 2;
            row["taken_code"] = rdoCode.Checked ? cboCode.SelectedValue : rdoPlan.Checked ? cboType.SelectedValue : cboSector.SelectedValue;
            row["client_taken_id"] = client_taken_id;
            row["surv_code"] = cboPointSurveillance.SelectedValue;
            row["taken_point_code"] = cboPointTaken.SelectedValue;
            row["taken_point_label"] = txtTakenLable.Text;
            row["taken_point_modifiable"] = chkPoint.Checked;
            row["taken_date"] = dtpTaken.Value.Date;
            if (Tag != null && taken_copy_id == 0)
            {
                if (txtTakenNext.Text.Trim() == "")
                    row["taken_date_next"] = DBNull.Value;
                else
                    row["taken_date_next"] = dtpTakenNext.Value.Date;
            }
            else
                row["taken_date_next"] = dtpTaken.Value.Date;
            //if (Tag != null && taken_copy_id == 0)
            //{
            //    row["taken_date_last"] = dtpTakenLast.Value.Date;
            //}
            //else
            //    row["taken_date_last"] = DBNull.Value;
            row["days_taken"] = sday;
            row["months_taken"] = smonth;
            row["years_taken"] = sweek;
            row["taken_comment"] = txtComment.Text;
            row["taken_point_day"] = numTaken.Value;
            String systemDecimalSeperator = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
            String strAmount = txtAmount.Text.Replace(",", systemDecimalSeperator);
            strAmount = strAmount.Replace(".", systemDecimalSeperator);
            row["amount"] = txtAmount.Text == "" ? 0 : decimal.Parse(strAmount);
            row["user_create"] = conf.CurUser;
            row["date_create"] = db.GetDate();

            // If form's Tag is null -> create new zone.
            // If from's Tag not null -> modify zone. (Tag is zone_id for modify)
            if (this.Tag == null)
            {
                // Check Identifiation dublicate field.
                //if (db.ExecuteScalar(string.Format(query.get_takenId, db.SqlString(cboCode.SelectedValue), client_taken_id)) != "")
                //{
                //    MessageBox.Show(msg.cont_takenProductExistMsg, msg.captionMsg, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                //    cboCode.Focus();
                //    return;
                //}

                if (MessageBox.Show(msg.saveMsg, msg.captionMsg, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.No) return;

                    // Add taken record into database.
                ananlyse_refresh = false;
                if (taken_copy_id == 0)
                    k_taken.Rows.Add(row);
                else
                {
                    taken_copy_id = 0;
                    k_taken.Rows[0].ItemArray = row.ItemArray;
                    k_taken.AcceptChanges();
                    k_taken.Rows[0].SetAdded();
                }
                ananlyse_refresh = true;
                    db.CommandBuilder(string.Format(query.get_taken, 0), k_taken);

                    this.Tag = db.ExecuteScalar(string.Format(query.get_takenId));

                    foreach (DataRow r in k_taken_analyze.Rows)
                    {
                        r["taken_id"] = this.Tag;
                        r["user_create"] = conf.CurUser;
                        r["date_create"] = db.GetDate();
                        r.AcceptChanges();
                        r.SetAdded();
                    }
                    db.CommandBuilder(string.Format(query.get_analy_taken, 0), k_taken_analyze);
            }
            else
            {
                // Check Identifiation dublicate field.
                string taken_id = db.ExecuteScalar(string.Format(query.get_takenId));
                //if (taken_id != "" && taken_id != k_taken.Rows[0]["taken_id"].ToString())
                //{
                //    MessageBox.Show(msg.cont_takenProductExistMsg, msg.captionMsg, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                //    cboCode.Focus();
                //    return;
                //}

                if (MessageBox.Show(msg.saveMsg, msg.captionMsg, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.No) return;
                
                    // Update contract into database.
                    ananlyse_refresh = false;
                    row["taken_id"] = this.Tag;
                    k_taken.Rows[0].ItemArray = row.ItemArray;
                    ananlyse_refresh = true;
                    db.CommandBuilder(string.Format(query.get_taken, 0), k_taken);

                    foreach (DataRow r in k_taken_analyze.Rows)
                    {
                        r["taken_id"] = this.Tag;
                        r["user_create"] = conf.CurUser;
                        r["date_create"] = db.GetDate();
                        r.AcceptChanges();
                        r.SetAdded();
                    }
                    db.ExecuteNonQuery(string.Format(query.del_analy_taken, this.Tag));
                    db.CommandBuilder(string.Format(query.get_analy_taken, 0), k_taken_analyze);
                

            }
            
            this.DialogResult = System.Windows.Forms.DialogResult.OK;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show(msg.exitSaveMsg, msg.captionMsg, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.No) return;
            Close();
        }

        private void chkPoint_CheckedChanged(object sender, EventArgs e)
        {
            txtTakenLable.ReadOnly = !chkPoint.Checked;
        }

        private void cboPointTaken_SelectedIndexChanged(object sender, EventArgs e)
        {
           if (cboPointTaken.SelectedIndex != -1) txtTakenLable.Text = PTPREL.Select(string.Format("PP_CODSURV='{0}'", cboPointTaken.Text))[0]["PP_LIBELLE"].ToString();
        }

        private void chk_m_1_CheckedChanged(object sender, EventArgs e)
        {
            if (!week_refesh) return;
            CheckBox chk = (CheckBox)sender;
            CalendarWeekRule weekRule = CalendarWeekRule.FirstFourDayWeek;
            Calendar calendar = System.Threading.Thread.CurrentThread.CurrentCulture.Calendar;
            DateTime beginningOfMonth = new DateTime(dtpTaken.Value.Year, int.Parse(chk.Tag.ToString()), 1);

            for (int i = 0; i <= DateTime.DaysInMonth(dtpTaken.Value.Year, int.Parse(chk.Tag.ToString())); i++ )
            {
                int currentWeek = calendar.GetWeekOfYear(beginningOfMonth.AddDays(i), weekRule, CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek);
                if (currentWeek > 52) return;
                if (week_load) taken_week[currentWeek - 1].Checked = chk.Checked;
                taken_week[currentWeek-1].Enabled = chk.Checked;
            }
            
           //MessageBox.Show(GetWeekOfMonth(dtpTaken.Value).ToString());
        }

        public static int GetWeekOfMonth(DateTime date)
        {
            DateTime beginningOfMonth = new DateTime(date.Year, date.Month, 1);

            while (date.Date.AddDays(1).DayOfWeek != System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek)
                date = date.AddDays(1);

            return (int)Math.Truncate((double)date.Subtract(beginningOfMonth).TotalDays / 7f) + 1;
        }

        private void cboCode_TextChanged(object sender, EventArgs e)
        {
            ComboBox cbo = (ComboBox)sender;
            if ((cbo == cboCode && !rdoCode.Checked) || (cbo != cboCode && rdoCode.Checked)) return;
            analyses_List(int.Parse(cbo.Tag.ToString()));
        }

        private void txtDateTaken_Validated(object sender, EventArgs e)
        {
            (new Libraies.ctl()).DateTimeTextBox(txtDateTaken, dtpTaken);
        }

        private void dtpTaken_ValueChanged(object sender, EventArgs e)
        {
            txtDateTaken.Text = dtpTaken.Value.Date.ToString("dd/MM/yyyy");
        }

        private void txtTakenStart_Validated(object sender, EventArgs e)
        {
            (new Libraies.ctl()).DateTimeTextBox(txtTakenNext, dtpTakenNext, true);
        }

        private void dtpTakenStart_ValueChanged(object sender, EventArgs e)
        {
            txtTakenNext.Text = dtpTakenNext.Value.Date.ToString("dd/MM/yyyy");
        }

        private void txtTakenDateLast_Validated(object sender, EventArgs e)
        {
            (new Libraies.ctl()).DateTimeTextBox(txtTakenLast, dtpTakenLast);
        }

        private void dtpTakenLast_ValueChanged(object sender, EventArgs e)
        {
            txtTakenLast.Text = dtpTakenLast.Value.Date.ToString("dd/MM/yyyy");
        }

        private void txtAmount_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar)
            && !char.IsDigit(e.KeyChar)
            && e.KeyChar != '.' && e.KeyChar != ',')
                {
                    e.Handled = true;
                }

                // only allow one decimal point
                if ((e.KeyChar == '.'
                    && (sender as TextBox).Text.IndexOf('.') > -1) || (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf(',') > -1))
                {
                    e.Handled = true;
                }

                // only allow one decimal point
                if ((e.KeyChar == ','
                    && (sender as TextBox).Text.IndexOf('.') > -1) || (e.KeyChar == ',' && (sender as TextBox).Text.IndexOf(',') > -1))
                {
                    e.Handled = true;
                }
                
        }

    }
}
